package utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

/**
 * Created by WF on 2020/7/27 15:51
 */
@ConfigurationProperties("jwt.config")
@Data
public class JwtUtil {
    private long ttl;
    private String key;

    //1.创建token
    public String createJWT(String id, String subject, String roles){
        //1.1)生成jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setIssuedAt(new Date())
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("roles",roles);
        //1.2)设置过期时间
        if(ttl >0){
            jwtBuilder.setExpiration(new Date(System.currentTimeMillis() + ttl));
        }
        //1.3）返回
        return jwtBuilder.compact();
    }
    //2.解析token
    public Claims parseToken(String token){
        Claims claims = Jwts.parser().setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
        return claims;

    }
}
